import React from 'react';
import api from './api';
import { requestGuard } from '../utils/requestGuard';
import {
  DashboardOutlined,
  TableOutlined,
  SettingOutlined,
  UserOutlined,
  TeamOutlined,
  AppstoreOutlined,
  BranchesOutlined,
  SafetyOutlined,
  DatabaseOutlined,
  LineChartOutlined,
  BarChartOutlined,
  PieChartOutlined,
  FileTextOutlined,
  FolderOutlined,
  CloudOutlined,
  ApiOutlined,
  MonitorOutlined,
  ToolOutlined,
  SecurityScanOutlined,
  AuditOutlined,
  ProfileOutlined,
  ContactsOutlined,
  GlobalOutlined,
  HomeOutlined,
  MenuOutlined,
  ControlOutlined,
  DeploymentUnitOutlined,
  ClusterOutlined,
  NodeIndexOutlined,
  PartitionOutlined,
} from '@ant-design/icons';

// 图标映射 - 扩展更多图标支持
const iconMap: Record<string, React.ComponentType> = {
  DashboardOutlined,
  TableOutlined,
  SettingOutlined,
  UserOutlined,
  TeamOutlined,
  AppstoreOutlined,
  BranchesOutlined,
  SafetyOutlined,
  DatabaseOutlined,
  LineChartOutlined,
  BarChartOutlined,
  PieChartOutlined,
  FileTextOutlined,
  FolderOutlined,
  CloudOutlined,
  ApiOutlined,
  MonitorOutlined,
  ToolOutlined,
  SecurityScanOutlined,
  AuditOutlined,
  ProfileOutlined,
  ContactsOutlined,
  GlobalOutlined,
  HomeOutlined,
  MenuOutlined,
  ControlOutlined,
  DeploymentUnitOutlined,
  ClusterOutlined,
  NodeIndexOutlined,
  PartitionOutlined,
};



// 菜单项接口 - 支持字符串类型的图标名称
export interface MenuItem {
  key: string;
  icon?: string; // 存储图标名称字符串
  label: string;
  children?: MenuItem[];
  permission?: string | string[];
}

// 路由响应接口
interface RouteResponse {
  id: number;
  path: string;
  name: string;
  display_name: string;
  description?: string;
  icon?: string;
  component?: string;
  parent_id?: number;
  sort_order: number;
  is_menu: boolean;
  is_active: boolean;
  is_system: boolean;
  meta?: Record<string, any>;
  children?: RouteResponse[];
  permissions?: Permission[];
  permission_names?: string[];
}

interface Permission {
  id: number;
  name: string;
  display_name: string;
  description?: string;
}

class MenuService {
  private menuCache: MenuItem[] | null = null;
  private cacheTime: number = 0;
  private readonly CACHE_DURATION = 1 * 60 * 1000; // 1分钟缓存（测试期间）
  private readonly STORAGE_KEY = 'dataplexus_menu_cache';
  private readonly STORAGE_TIME_KEY = 'dataplexus_menu_cache_time';
  private renderCount = 0;

  /**
   * 从localStorage加载菜单缓存
   */
  private loadFromStorage(): { menuItems: MenuItem[] | null; cacheTime: number } {
    try {
      const storedMenu = localStorage.getItem(this.STORAGE_KEY);
      const storedTime = localStorage.getItem(this.STORAGE_TIME_KEY);

      if (storedMenu && storedTime) {
        const menuItems = JSON.parse(storedMenu) as MenuItem[];
        const cacheTime = parseInt(storedTime, 10);

        // 检查存储的数据是否有效
        if (Array.isArray(menuItems) && !isNaN(cacheTime)) {
          return { menuItems, cacheTime };
        }
      }
    } catch (error) {
      console.warn('从localStorage加载菜单缓存失败:', error);
    }

    return { menuItems: null, cacheTime: 0 };
  }

  /**
   * 保存菜单到localStorage
   */
  private saveToStorage(menuItems: MenuItem[], cacheTime: number): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(menuItems));
      localStorage.setItem(this.STORAGE_TIME_KEY, cacheTime.toString());
    } catch (error) {
      console.warn('保存菜单到localStorage失败:', error);
    }
  }

  /**
   * 获取用户菜单（完全基于API）- 优化版本
   */
  async getUserMenu(forceRefresh = false): Promise<MenuItem[]> {
    const now = Date.now();

    // 初始化时从localStorage加载缓存
    if (!this.menuCache && !forceRefresh) {
      const { menuItems, cacheTime } = this.loadFromStorage();
      if (menuItems && (now - cacheTime) < this.CACHE_DURATION) {
        this.menuCache = menuItems;
        this.cacheTime = cacheTime;
        console.log('📱 从localStorage加载菜单缓存');
        return menuItems;
      }
    }

    // 如果有内存缓存且未过期，直接返回缓存（除非强制刷新）
    if (!forceRefresh && this.menuCache && (now - this.cacheTime) < this.CACHE_DURATION) {
      return this.menuCache;
    }

    try {
      // 使用requestGuard防止重复请求，但允许权限变更时的刷新
      const requestKey = forceRefresh ? `getUserMenu_${now}` : 'getUserMenu';
      if (!requestGuard.canRequest(requestKey)) {
        // 如果有任何形式的缓存，返回缓存
        if (this.menuCache) {
          return this.menuCache;
        }

        // 尝试从localStorage获取备用数据
        const { menuItems } = this.loadFromStorage();
        if (menuItems) {
          console.log('🔄 使用localStorage备用菜单数据');
          return menuItems;
        }

        return [];
      }

      console.log('🌐 从API获取菜单数据');
      const response = await api.get('/v1/routes/menu');
      const routes: RouteResponse[] = response.data.data;

      // 转换为菜单项
      const menuItems = this.convertRoutesToMenuItems(routes);

      // 更新内存缓存
      this.menuCache = menuItems;
      this.cacheTime = now;

      // 保存到localStorage
      this.saveToStorage(menuItems, now);

      requestGuard.completeRequest(requestKey);
      return menuItems;
    } catch (error) {
      console.error('获取用户菜单失败:', error);
      requestGuard.completeRequest(forceRefresh ? `getUserMenu_${now}` : 'getUserMenu');

      // 优先返回内存缓存
      if (this.menuCache) {
        console.log('⚠️ API失败，使用内存缓存');
        return this.menuCache;
      }

      // 尝试从localStorage获取备用数据
      const { menuItems } = this.loadFromStorage();
      if (menuItems) {
        console.log('⚠️ API失败，使用localStorage备用数据');
        this.menuCache = menuItems; // 同步到内存缓存
        return menuItems;
      }

      // 完全没有缓存时才抛出错误
      throw new Error('菜单加载失败，请检查网络连接或联系管理员');
    }
  }

  /**
   * 将路由数据转换为菜单项
   */
  private convertRoutesToMenuItems(routes: RouteResponse[]): MenuItem[] {


    const menuItems = routes
      .filter(route => route.is_menu && route.is_active)
      .sort((a, b) => a.sort_order - b.sort_order)
      .map(route => {
        const menuItem = this.convertRouteToMenuItem(route);

        return menuItem;
      });

    return menuItems;
  }

  /**
   * 转换单个路由为菜单项 - 修复图标处理
   */
  private convertRouteToMenuItem(route: RouteResponse): MenuItem {
    const menuItem: MenuItem = {
      key: route.path,
      label: route.display_name,
    };

    // 设置图标 - 使用字符串存储图标名称，在渲染时再转换
    if (route.icon && iconMap[route.icon]) {
      // 存储图标名称而不是组件
      menuItem.icon = route.icon as any; // 临时存储图标名称

    } else {
      // 使用默认图标名称
      menuItem.icon = 'AppstoreOutlined' as any;

    }

    // 设置权限要求
    if (route.permission_names && route.permission_names.length > 0) {
      menuItem.permission = route.permission_names.length === 1
        ? route.permission_names[0]
        : route.permission_names;
    }

    // 处理子菜单
    if (route.children && route.children.length > 0) {
      menuItem.children = this.convertRoutesToMenuItems(route.children);
    }

    return menuItem;
  }

  /**
   * 重置渲染计数器
   */
  resetRenderCount(): void {
    this.renderCount = 0;
  }

  /**
   * 清除菜单缓存
   */
  clearCache(): void {
    this.menuCache = null;
    this.cacheTime = 0;

    // 同时清除localStorage缓存
    try {
      localStorage.removeItem(this.STORAGE_KEY);
      localStorage.removeItem(this.STORAGE_TIME_KEY);
    } catch (error) {
      console.warn('清除localStorage菜单缓存失败:', error);
    }
  }

  /**
   * 强制重新加载菜单（用于调试）
   */
  async forceReload(): Promise<MenuItem[]> {
    this.clearCache();
    return await this.getUserMenu(true);
  }

  /**
   * 获取加载状态信息
   */
  getLoadingStatus(): {
    hasCache: boolean;
    hasBackup: boolean;
    cacheAge: number;
    lastUpdate: string;
  } {
    const now = Date.now();
    const { menuItems: storageItems, cacheTime: storageTime } = this.loadFromStorage();

    return {
      hasCache: !!this.menuCache,
      hasBackup: !!storageItems,
      cacheAge: this.cacheTime ? now - this.cacheTime : 0,
      lastUpdate: this.cacheTime ? new Date(this.cacheTime).toLocaleString() : '未知'
    };
  }

  /**
   * 根据权限过滤菜单项（优化版本）
   */
  filterMenuByPermissions(
    menuItems: MenuItem[],
    hasPermission: (permission: string) => boolean
  ): MenuItem[] {
    const filteredItems: MenuItem[] = [];

    for (const item of menuItems) {
      // 检查当前项权限
      if (item.permission) {
        let hasRequiredPermission = false;

        if (typeof item.permission === 'string') {
          // 单个权限
          hasRequiredPermission = hasPermission(item.permission);
        } else if (Array.isArray(item.permission)) {
          // 权限数组 - 需要拥有所有权限
          hasRequiredPermission = item.permission.every(perm => hasPermission(perm));
        }

        if (!hasRequiredPermission) {
          continue;
        }
      }

      // 创建新的菜单项（避免修改原始数据）
      const newItem: MenuItem = { ...item };

      // 如果有子菜单，递归过滤
      if (item.children && item.children.length > 0) {
        const filteredChildren = this.filterMenuByPermissions(item.children, hasPermission);

        // 只有当子菜单不为空或者当前项本身有路由时才保留
        if (filteredChildren.length > 0 || item.key.startsWith('/')) {
          newItem.children = filteredChildren;
          filteredItems.push(newItem);
        }
      } else {
        // 叶子节点直接添加
        filteredItems.push(newItem);
      }
    }

    return filteredItems;
  }

  /**
   * 实时权限检查（用于权限变更后立即生效）
   */
  async refreshMenuWithPermissions(hasPermission: (permission: string) => boolean): Promise<MenuItem[]> {
    // 清除缓存，强制重新获取
    this.clearCache();

    try {
      const menuItems = await this.getUserMenu(true);
      return this.filterMenuByPermissions(menuItems, hasPermission);
    } catch (error) {
      console.error('刷新菜单权限失败:', error);
      return [];
    }
  }
}

// 导出单例
export const menuService = new MenuService();
export default menuService;
